<?php

namespace app\admin\controller\warehouse;

use app\admin\model\in\Inventory;
use app\admin\model\InventoryItemInfo;
use app\admin\model\out\OutInventoryAddr;
use app\common\controller\Backend;
use think\Config;
use think\Db;

/**
 * 库存一览
 * Class Inventorylist
 * @package app\admin\controller\warehouse
 */
class Inventorylist extends Backend
{

    protected $model = null;
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'uid';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\inventory\Lists;

    }


    public function index()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $wms = $this->getWarehouse();
            //将仓库补充到 rows 数组中去
            foreach ($list as $key => $value) {
                foreach ($wms as $val) {
                    if ($value['warehouseid'] == $val['code']) {
                        $list[$key]['warehouseid'] = $val['name'];
                    }
                }
            }
            $result = array("total" => $total, "rows" => $list,"wms"=>$wms);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 入库申请
     * @param null $ids
     * @return string
     */
    public function inWarehouse($ids = NULL)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //判断是否存在商品空数量
                    foreach ($params['itemnum'] as $item){
                        if($item<1){
                            $this->error('请填写入库商品数量');
                        }
                    }
                    Db::startTrans();
                    $inData['count'] = $params['inventorycount'];
                    $inData['warehouseid'] = $params['warehouseid'];
                    $inData['remark'] = $params['remark'];
                    $inorderid =  'IN'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                    $inData['inorderid'] =$inorderid;
                    $inData[$this->dataLimitField] = $this->auth->aid;

                    $inInventory = new Inventory;

                    $result = $inInventory->save($inData);
                    $inid = $inInventory->getLastInsID();
                    if(!empty($inid) && $result !== false){
                        //保存入库关联商品
                        for($i=0;$i< count($params['itemid']);$i++){
                            $data['itemsku'] = $params['itemsku'][$i];
                            $data['itemid'] = $params['itemid'][$i];
                            $data['itemname'] = $params['itemname'][$i];
                            $data['instoragecount'] = $params['itemnum'][$i];
                            $data['type'] = 1;
                            $data['inid'] = $inid;
                            $data['orderId'] = $inorderid;
                            $data['warehouseid'] = $params['warehouseid'];

                            $inItemInfo = new InventoryItemInfo;
                            $rsItem = $inItemInfo->save($data);
                            if($rsItem === false){
                                Db::rollback();
                                $this->error('入库申请失败，请重试');
                            }
                        }
                        Db::commit();
                        $this->success();
                    }else{
                        $this->error('入库申请失败，请重试');
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
        $items = collection($list)->toArray();
        $wms = $this->getWarehouse();


        $this->view->assign("items", $items);
        $this->view->assign("wms", $wms);
        return $this->view->fetch();
    }

    /*
     * 出库申请
     */
    public function outWarehouse($ids = NULL)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //判断是否存在商品空数量
                    foreach ($params['itemnum'] as $item){
                        if($item<1){
                            $this->error('请填写出库商品数量');
                        }
                    }
                    //查找商品对应库存数量 判断库存情况 进行提醒

                    Db::startTrans();
                    $inData['warehouseid'] = $params['warehouseid'];
                    $inData['file'] = $params['file'];
                    $inData['remark'] = $params['remark'];
                    $inData['orderid'] = $params['orderid'];
                    $inOrderId = 'OUT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                    $inData['outorderid'] = $inOrderId;
                    $inData[$this->dataLimitField] = $this->auth->aid;

                    $outInventory = new \app\admin\model\out\Inventory;

                    $result = $outInventory->save($inData);
                    $outid = $outInventory->getLastInsID();
                    if(!empty($outid) && $result !== false){
                        //保存出库关联商品
                        for($i=0;$i< count($params['itemid']);$i++){
                            $data['itemsku'] = $params['itemsku'][$i];
                            $data['itemid'] = $params['itemid'][$i];
                            $data['itemname'] = $params['itemname'][$i];
                            $data['instoragecount'] = $params['itemnum'][$i];
                            $data['type'] = 2;
                            $data['inid'] = $outid;
                            $data['orderId'] = $inOrderId;
                            $data['warehouseid'] = $params['warehouseid'];


                            $inItemInfo = new InventoryItemInfo;
                            $rsItem = $inItemInfo->save($data);
                            if($rsItem === false){
                                Db::rollback();
                                $this->error('入库申请失败，请重试');
                            }
                        }
                        //保存出库发货地址
                        $address['recipients']= $params['recipients'];
                        $address['mobile']= $params['mobile'];
                        $address['company']= $params['company'];
                        $address['state']= $params['state'];
                        $address['province']= $params['province'];
                        $address['city']= $params['city'];
                        $address['postcode']= $params['postcode'];
                        $address['addressone']= $params['addressone'];
                        $address['addresstwo']= $params['addresstwo'];
                        $address['outid']= $outid;
                        $address['outorderid']= $inOrderId;
                        $outInventoryAddr = new OutInventoryAddr;
                        $outInventoryAddr->save($address);

                        Db::commit();
                        $this->success();
                    }else{
                        $this->error('出库申请失败，请重试');
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
        $items = collection($list)->toArray();
        $wms = $this->getWarehouse();
        $global = Config::get("global");
        $this->view->assign("global",$global);
        $this->view->assign("items", $items);
        $this->view->assign("wms", $wms);
        return $this->view->fetch();

    }

   public function record($ids){
       $ids = $ids ? $ids : $this->request->param("ids");

       $row = $this->model->get($ids)->toArray();
       $row = collection($row)->toArray();
       if ($this->request->isAjax()) {
           if ($this->request->request('keyField')) {
               return $this->selectpage();
           }

           $filter = $_GET['filter'];
           $filter = json_decode($filter,true);
           $where = ["itemid"=>["eq",$row['sku']]];

           if(!empty($filter)){
                if(isset($filter['type'])){
                    $where['type'] = ["eq",$filter['type']];
                }
               if(isset($filter['warehouseid'])){
                   $where['warehouseid'] = ["eq",$filter['warehouseid']];
               }

               if(isset($filter['createtime'])){
                   $start = strtotime(substr($filter['createtime'],0,19));
                   $end = strtotime(substr($filter['createtime'],22));
                   $where['createtime'] = [">=",$start];
                   //$where['createtime'] = ["<=",$end];
               }
           }

            //增加搜索条件
           $sort = $this->request->get("sort", "id");
           $order = $this->request->get("order", "DESC");
           $offset = $this->request->get("offset", 0);
           $limit = $this->request->get("limit", 0);
           $itemInfo = model('InventoryItemInfo');
           $total = $itemInfo
               ->where($where)
               ->order($sort, $order)
               ->count();

           $list = $itemInfo
               ->where($where)
               ->order($sort, $order)
               ->limit($offset, $limit)
               ->select();

           $list = collection($list)->toArray();
           $wms = $this->getWarehouse();
           //将仓库补充到 rows 数组中去
           foreach ($list as $key => $value) {
               foreach ($wms as $val) {
                   if ($value['warehouseid'] == $val['code']) {
                       $list[$key]['warehouseid'] = $val['name'];
                   }
               }
           }
           $result = array("total" => $total, "rows" => $list,"wms"=>$wms);

           return json($result);
       }
       $this->view->assign("ids", $ids);
       return $this->view->fetch();
   }

   public function add(){
       if ($this->request->isAjax()) {
           $this->error();
       }
       return $this->view->fetch();
   }

    /**
     * 获取仓库
     * @return array|false|\PDOStatement|string|\think\Collection
     */
   public function getWarehouse(){

       $wmsModel = model('Warehouse');
       $wms = $wmsModel->select();
       $wms = collection($wms)->toArray();

       return $wms;
   }



}
